<?php
require_once '../config.php';

function debug()
{
	static $debug = array();

	if (!func_num_args())
		return $debug;

	ob_start();
	call_user_func_array('var_dump', func_get_args());
	$debug[] = ob_get_contents();
	ob_end_clean();
}

$player = U1_Player::getSession();
$planets = $player->offsetGet(U1_Planet::INDEX);

$page = null;
if (isset($_GET['page']) && !empty($_GET['page']))
{
	$page = (string)$_GET['page'];
	if (false !== strpos($page, '/') || !file_exists('view/'.$page.'.php'))
		$page = null;
}

$page = array(
	'css' => array('general.css'),
	'view' => $page ?: 'structure',
	'vars' => array(),
	'js' => array(),
	'datetime' => new DateTime('now', new DateTimeZone('Europe/Paris')),
	'requestKeep' => array()
);

try{
	$planets->setCurrentId($_GET['select_planet']);
}
catch(Exception $e)
{}

///@include action/*.php
require 'action/'.$page['view'].'.php';


foreach ($planets as $id => $planet)
	U1_Render::addPlanet($id, $planet);

debug($page['vars'] ? $page['vars'] : 'no vars');

try {
	ob_start();
	debug($_POST, $_GET);
	///@include view/*.php
	require 'view/'.$page['view'].'.php';
	$view = ob_get_contents();
	ob_end_clean();
}
catch (/*Error*/Exception $e)
{
	$view = XMLIndent::asText(ob_get_contents());
	ob_end_clean();

	echo '<pre>'.$view.'</pre>'.implode('', debug());

	//pour passé la main à xdebug
	throw $e;
}

if (!isset($_GET['out']) || $_GET['out'] !== 'html')
	header('Content-Type: text/xml; charset=utf-8');
$debug = debug();

$requestKeep = '';
foreach ($page['requestKeep'] as $k => $v)
	$requestKeep .= '<value name="'.$k.'">'.$v.'</value>';

echo '<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="xsl/'.(isset($page['xsl']) ? $page['xsl'] : $page['view'].'.xsl').'"?>

<sun-wars universe="0-alpha" id-player="'.$player->getId().'" id-planet-current="'.$planets->getCurrentId().'" lang="fr" datetime="'.$page['datetime']->format(DateTime::W3C).'">
	<page name="index.php?page='.$page['view'].'">
		<title>'.(isset($page['title']) ? $page['title'] : $page['view']).'</title>'
		.($requestKeep ? '<request-keep>'.$requestKeep.'</request-keep>' : null)
		.($page['js'] ? '<scripts><js>'.implode('</js><js>', $page['js']).'</js></scripts>' : null)
		.($page['css'] ? '<styles><css>'.implode('</css><css>', $page['css']).'</css></styles>' : null).'
	</page>'
	.($debug ? '<debug>'.implode('</debug><debug>', $debug).'</debug>' : '')
	.U1_Render::render()
	.$view.'
</sun-wars>';